<template>
    <div class="app-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="left">
                <el-button link @click="goBack">
                    <el-icon><ArrowLeft /></el-icon>
                    返回商品列表
                </el-button>
                <div class="title">SKU管理</div>
                <el-tag
                    type="info"
                    effect="plain"
                    class="product-name"
                >
                    {{ productStore.productInfo.productsName }}
                    
                </el-tag>
                <el-tag 
                        :type="productStore.productInfo.status === '1' ? 'success' : 'info'"
                        size="small"
                        class="ml-2"
                    >
                        {{ productStore.productInfo.status === '1' ? '在售' : '下架' }}
                    </el-tag>
            </div>
            <div class="right">
                <el-button type="primary" @click="handleBatchPrice" :icon="Money">批量设置价格</el-button>
                <el-button type="primary" @click="handleBatchStock" :icon="Box">批量设置库存</el-button>
                <el-button type="success" @click="handleSave" :icon="Check">保存</el-button>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
            <el-card class="sku-list">
                <template #header>
                    <div class="card-header">
                        <div class="header-left">
                            <span class="card-title">SKU列表</span>
                            <el-tag type="info" effect="plain" class="count-tag">共 {{ productStore.skus.length }} 个</el-tag>
                        </div>
                        <div class="header-right">
                            <el-button type="primary" @click="handleGenerateSku" :icon="Plus">生成SKU</el-button>
                        </div>
                    </div>
                </template>

                <el-table
                    v-loading="loading"
                    :data="productStore.skus"
                    border
                    style="width: 100%"
                >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column label="图片" width="100" align="center">
                        <template #default="{ row }">
                            <el-upload
                                class="sku-image-upload"
                                :action="uploadUrl"
                                :headers="headers"
                                :show-file-list="false"
                                :before-upload="beforeUpload"
                                :on-success="(res) => handleUploadSuccess(res, row)"
                            >
                                <el-image
                                    v-if="row.image"
                                    :src="row.image"
                                    fit="cover"
                                    class="sku-image"
                                />
                                <el-icon v-else class="upload-icon"><Plus /></el-icon>
                            </el-upload>
                        </template>
                    </el-table-column>
                    <el-table-column label="规格组合" min-width="200">
                        <template #default="{ row }">
                            <div class="spec-combination">
                                <el-tag
                                    v-for="spec in row.specs"
                                    :key="spec.name"
                                    class="spec-tag"
                                    effect="plain"
                                >
                                    {{ spec.name }}: {{ spec.value }}
                                </el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" label="价格" width="180">
                        <template #default="{ row }">
                            <el-input-number
                                v-model="row.price"
                                :min="0"
                                :precision="2"
                                :step="0.1"
                                controls-position="right"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" width="180">
                        <template #default="{ row }">
                            <el-input-number
                                v-model="row.stock"
                                :min="0"
                                controls-position="right"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="商品编码" min-width="150">
                        <template #default="{ row }">
                            <el-input v-model="row.code" placeholder="请输入商品编码" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>

        <!-- 生成SKU弹窗 -->
        <el-dialog
            v-model="generateDialog.visible"
            title="生成SKU"
            width="600px"
            destroy-on-close
        >
            <el-form
                ref="generateFormRef"
                :model="generateForm"
                :rules="generateRules"
                label-width="100px"
            >
                <el-form-item
                    v-for="(spec, index) in generateForm.specs"
                    :key="index"
                    :label="'规格' + (index + 1)"
                    :prop="'specs.' + index + '.values'"
                    :rules="{ required: true, message: '请选择规格值', trigger: 'change' }"
                >
                    <div class="spec-form-item">
                        <el-select
                            v-model="spec.name"
                            placeholder="请选择规格名称"
                            class="spec-name-select"
                            @change="handleSpecNameChange(index)"
                        >
                            <el-option
                                v-for="item in specOptions"
                                :key="item.name"
                                :label="item.name"
                                :value="item.name"
                            />
                        </el-select>
                        <el-select
                            v-model="spec.values"
                            multiple
                            placeholder="请选择规格值"
                            class="spec-values-select"
                            :disabled="!spec.name"
                        >
                            <el-option
                                v-for="value in getSpecValues(spec.name)"
                                :key="value"
                                :label="value"
                                :value="value"
                            />
                        </el-select>
                        <el-button
                            type="danger"
                            :icon="Delete"
                            circle
                            @click="removeSpec(index)"
                        />
                    </div>
                </el-form-item>
                <el-form-item v-if="generateForm.specs.length < 3">
                    <el-button type="primary" :icon="Plus" @click="addSpec">添加规格</el-button>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="generateDialog.visible = false">取 消</el-button>
                    <el-button type="primary" @click="submitGenerateForm">确 定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 批量设置价格弹窗 -->
        <el-dialog
            v-model="batchPriceDialog.visible"
            title="批量设置价格"
            width="400px"
            destroy-on-close
        >
            <el-form
                ref="batchPriceFormRef"
                :model="batchPriceForm"
                :rules="batchPriceRules"
                label-width="100px"
            >
                <el-form-item label="价格" prop="price">
                    <el-input-number
                        v-model="batchPriceForm.price"
                        :min="0"
                        :precision="2"
                        :step="0.1"
                        controls-position="right"
                        class="w-full"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="batchPriceDialog.visible = false">取 消</el-button>
                    <el-button type="primary" @click="submitBatchPrice">确 定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 批量设置库存弹窗 -->
        <el-dialog
            v-model="batchStockDialog.visible"
            title="批量设置库存"
            width="400px"
            destroy-on-close
        >
            <el-form
                ref="batchStockFormRef"
                :model="batchStockForm"
                :rules="batchStockRules"
                label-width="100px"
            >
                <el-form-item label="库存" prop="stock">
                    <el-input-number
                        v-model="batchStockForm.stock"
                        :min="0"
                        controls-position="right"
                        class="w-full"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="batchStockDialog.visible = false">取 消</el-button>
                    <el-button type="primary" @click="submitBatchStock">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
    ArrowLeft,
    Plus,
    Delete,
    Money,
    Box,
    Check
} from '@element-plus/icons-vue';
import { useProductStore } from '@/store/modules/product';
import { getToken } from '@/utils/auth';

const router = useRouter();
const route = useRoute();
const productStore = useProductStore();

// ===== 状态管理 =====
const loading = ref(false);
const formRef = ref(null);


// ===== 对话框管理 =====
const generateDialog = reactive({
    visible: false
});

const batchPriceDialog = reactive({
    visible: false
});

const batchStockDialog = reactive({
    visible: false
});

// ===== 表单数据 =====
const generateForm = reactive({
    specs: [
        { name: '', values: [] }
    ]
});

const batchPriceForm = reactive({
    price: 0
});

const batchStockForm = reactive({
    stock: 0
});

// ===== 表单验证规则 =====
const generateRules = {
    specs: [
        { required: true, message: '请至少添加一个规格', trigger: 'change' }
    ]
};

const batchPriceRules = {
    price: [
        { required: true, message: '请输入价格', trigger: 'blur' },
        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
    ]
};

const batchStockRules = {
    stock: [
        { required: true, message: '请输入库存', trigger: 'blur' },
        { pattern: /^\d+$/, message: '请输入正确的库存数量', trigger: 'blur' }
    ]
};

// ===== SKU 生成方法 =====
/**
 * 添加规格
 */
const addSpec = () => {
    if (generateForm.specs.length < 3) {
        generateForm.specs.push({ name: '', values: [] });
    }
};

/**
 * 移除规格
 * @param {number} index - 规格索引
 */
const removeSpec = (index) => {
    generateForm.specs.splice(index, 1);
};

/**
 * 规格名称改变处理
 * @param {number} index - 规格索引
 */
const handleSpecNameChange = (index) => {
    generateForm.specs[index].values = [];
};

/**
 * 生成 SKU 组合
 * @param {Array} specs - 规格数组
 * @returns {Array} SKU 组合数组
 */
const generateSkuCombinations = (specs) => {
    const combinations = [];
    const combine = (current, index) => {
        if (index === specs.length) {
            combinations.push([...current]);
            return;
        }
        const spec = specs[index];
        for (const value of spec.values) {
            current.push({ name: spec.name, value });
            combine(current, index + 1);
            current.pop();
        }
    };
    combine([], 0);
    return combinations;
};

// ===== 批量操作方法 =====
/**
 * 批量设置价格
 */
const handleBatchPrice = () => {
    if (productStore.skus.length === 0) {
        ElMessage.warning('请先生成SKU');
        return;
    }
    batchPriceDialog.visible = true;
};

/**
 * 批量设置库存
 */
const handleBatchStock = () => {
    if (productStore.skus.length === 0) {
        ElMessage.warning('请先生成SKU');
        return;
    }
    batchStockDialog.visible = true;
};

/**
 * 提交批量设置价格
 */
const submitBatchPrice = async () => {
    try {
        productStore.skus.forEach(sku => {
            sku.price = batchPriceForm.price;
        });
        batchPriceDialog.visible = false;
        ElMessage.success('批量设置价格成功');
    } catch (error) {
        console.error('批量设置价格失败:', error);
        ElMessage.error('批量设置价格失败');
    }
};

/**
 * 提交批量设置库存
 */
const submitBatchStock = async () => {
    try {
        productStore.skus.forEach(sku => {
            sku.stock = batchStockForm.stock;
        });
        batchStockDialog.visible = false;
        ElMessage.success('批量设置库存成功');
    } catch (error) {
        console.error('批量设置库存失败:', error);
        ElMessage.error('批量设置库存失败');
    }
};

// ===== SKU 操作方法 =====
/**
 * 生成 SKU
 */
const handleGenerateSku = () => {
    if (productStore.skus.length > 0) {
        ElMessageBox.confirm(
            '生成新的SKU将清空当前所有SKU数据，是否继续？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            generateDialog.visible = true;
        }).catch(() => {});
    } else {
        generateDialog.visible = true;
    }
};

/**
 * 提交生成 SKU 表单
 */
const submitGenerateForm = async () => {
    try {
        const validSpecs = generateForm.specs.filter(spec => spec.name && spec.values.length > 0);
        if (validSpecs.length === 0) {
            ElMessage.warning('请至少选择一个规格及其值');
            return;
        }

        const combinations = generateSkuCombinations(validSpecs);
        const newSkus = combinations.map((specs, index) => ({
            id: Date.now() + index,
            specs,
            price: 0,
            stock: 0,
            code: '',
            image: ''
        }));

        productStore.skus = newSkus;
        generateDialog.visible = false;
        ElMessage.success('SKU生成成功');
    } catch (error) {
        console.error('生成SKU失败:', error);
        ElMessage.error('生成SKU失败');
    }
};

/**
 * 保存 SKU
 */
const handleSave = async () => {
    try {
        if (productStore.skus.length === 0) {
            ElMessage.warning('请先生成SKU');
            return;
        }

        await productStore.updateSkus();
        ElMessage.success('保存成功');
        goBack();
    } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败');
    }
};

// ===== 图片上传相关 =====
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload";
const headers = { Authorization: 'Bearer ' + getToken() };

/**
 * 上传前校验
 * @param {File} file - 上传的文件
 */
const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
        ElMessage.error('只能上传图片文件！');
        return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB！');
        return false;
    }
    return true;
};

/**
 * 上传成功处理
 * @param {Object} res - 上传响应结果
 * @param {Object} row - SKU 数据行
 */
const handleUploadSuccess = (res, row) => {
    row.image = res.url;
    ElMessage.success('上传成功');
};

/**
 * 返回上一页
 */
const goBack = () => {
    router.go(-1);
};

// ===== 生命周期钩子 =====
onMounted(async () => {
    const productId = route.params.id;
    if (productId) {
        loading.value = true;
        try {
            await productStore.loadProductDetail(productId);
        } catch (error) {
            console.error('加载商品详情失败:', error);
            ElMessage.error('加载商品详情失败');
        } finally {
            loading.value = false;
        }
    }
});
</script>

<style lang="scss" scoped>
.app-container {
    background-color: #f5f7fa;
    min-height: calc(100vh - 84px);
    padding: 16px;
}

.page-header {
    height: 56px;
    line-height: 56px;
    background-color: #fff;
    padding: 0 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 4px;
    margin-bottom: 16px;

    .left {
        display: flex;
        align-items: center;
        gap: 16px;

        .title {
            font-size: 16px;
            font-weight: 500;
            color: #1f2f3d;
        }

        .product-name {
            margin-left: 8px;
        }
    }

    .right {
        display: flex;
        align-items: center;
        gap: 8px;
    }
}

.main-content {
    .sku-list {
        :deep(.el-card__header) {
            padding: 0;
        }

        .card-header {
            padding: 16px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #f0f0f0;

            .header-left {
                display: flex;
                align-items: center;
                gap: 12px;

                .card-title {
                    font-size: 14px;
                    font-weight: 500;
                    color: #1f2f3d;
                }

                .count-tag {
                    font-size: 12px;
                }
            }
        }
    }

    .spec-combination {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;

        .spec-tag {
            margin: 2px;
        }
    }

    .sku-image-upload {
        :deep(.el-upload) {
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            width: 80px;
            height: 80px;
            display: flex;
            justify-content: center;
            align-items: center;

            &:hover {
                border-color: var(--el-color-primary);
            }
        }

        .sku-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
        }

        .upload-icon {
            font-size: 24px;
            color: #8c939d;
        }
    }
}

.spec-form-item {
    display: flex;
    gap: 8px;
    align-items: flex-start;

    .spec-name-select {
        width: 140px;
    }

    .spec-values-select {
        flex: 1;
    }
}

.w-full {
    width: 100%;
}
</style> 